import Vue from 'vue'
import Vuex from 'vuex'
import http from '../js_sdk/luch-request/luch-request/index'

Vue.use(Vuex)

import localStorage from '../localStorage'
import config from '@/config'

const store = new Vuex.Store({
	state: {
		scene: 0, // 场景值
		hasLogin: false, // 是否已经登录
		userinfo: {}, // 登录用户信息
		businessList: [], // 绑定的商户
		menus: [],		// 系统菜单
	},
	getters: {
		// 默认商户
		defaultBusiness(state) {
			let arr = state.businessList.filter(a => a.id === state.userinfo.defaultBusiness)
			if (arr.length > 0) return arr[0]
			return undefined
		}
	},
	mutations: {
		// login(state, provider) {

		// 	state.hasLogin = true;
		// 	state.userInfo = provider;
		// 	uni.setStorage({//缓存用户登陆状态
		// 	    key: 'userInfo',  
		// 	    data: provider  
		// 	}) 
		// 	console.log(state.userInfo);
		// }
		// 设置场景值
		setScene(state, scene) {
			state.scene = scene
		},
		// 设置用户信息
		setUserInfo(state, info) {
			state.userinfo = info
			localStorage.setUserinfo(info)
		},
		// 设置是否登录授权
		setIsLogin(state, hasLogin) {
			state.hasLogin = !!hasLogin
		},
		// 设置用户绑定的商户
		setBusinessList(state, businesses) {
			state.businessList = businesses
		},
		// 新增绑定的商户
		addBusiness(state, business) {
			state.businessList.push(business)
		},
		// 移除门店
		removeBusiness(state, id) {
			state.businessList.remove(item => item.id === id)
		},
		// 设置用户绑定的商户
		setMenus(state, menues) {
			state.menus = menues
		},
	},
	actions: {
		// 获取根据code获取用户openid，读取用户
		async login({
			commit,
			state
		}) {
			let task = new Promise(function(resolve, reject) {
				uni.login({
					provider: 'weixin',
					async success(info) {
						let [, res] = await uni.request({
							url: `${config.baseURL}/account/token`,
							data: {
								code: info.code
							},
							method: 'POST'
						})
						let userinfo = res.data.data.data
						// 保存用户信息
						localStorage.setUserinfo(userinfo)
						// 保存token
						localStorage.setToken({ token: res.header['access-token'], 'x-token': res.header['x-access-token'] })
						resolve(userinfo)
					}
				})
			})
			let userinfo = await task

			commit('setUserInfo', userinfo)
			commit('setIsLogin', userinfo.isRegister)

		},
		// 系统初始化
		async appInit({
			commit
		}) {
			let {
				data
			} = await http.get('/mobile/init')
			commit('setBusinessList', data.businesses)
			commit('setMenus', data.menus)
		}
	}
})

export default store
